package org.hertsig.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;

import lombok.SneakyThrows;

import com.google.common.base.Charsets;
import com.google.common.io.CharSource;

public class ConnectionHelper {
	public static final int HTTP_OK = 200;
	public static final int HTTP_NO_CONTENT = 204;
	public static final int HTTP_PARTIAL_CONTENT = 206;
	public static final int HTTP_BAD_REQUEST = 400;
	
	@SneakyThrows(IOException.class)
	public static HttpURLConnection get(URL url) {
		return (HttpURLConnection) url.openConnection();
	}
	
	public static HttpURLConnection post(URL url) {
		return open(url, "POST");
	}
	
	public static HttpURLConnection put(URL url) {
		return open(url, "PUT");
	}
	
	public static HttpURLConnection delete(URL url) {
		return open(url, "DELETE");
	}
	
	@SneakyThrows(IOException.class)
	private static HttpURLConnection open(URL url, String method) {
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setDoOutput(true);
		connection.setRequestMethod(method);
		connection.setRequestProperty("Accept", "application/json");
		return connection;
	}
	
	@SneakyThrows(IOException.class)
	public static void copy(final InputStream source, Appendable target) {
		new CharSource() {
			@Override
			public Reader openStream() throws IOException {
				return new InputStreamReader(source, Charsets.UTF_8);
			}
		}.copyTo(target);
	}
}
